<template>
  <div>
    <h1>Order User View</h1>
    <OrderShow :orders="orders"
      @confirm="confirmOrder"
      @cancel="cancelOrder"
      @view="viewOrder">
    </OrderShow>
    <!--引入底部导航栏-->
    <foot-component
        :cart-count="cartCount"
        :current-path="$route.path"
        @navigate="handleNavigate"
    />
  </div>

</template>
<script>
import OrderShow from '@/components/order/OrderShowComponent';
import FootComponent from '@/components/product/FootComponent.vue';
import axios from 'axios'
export default {
  name: 'OrderUserView',
  props:['cartId'],//接收cartId参数
  components: {
    OrderShow,
    FootComponent
  },
  data() {
    return{
      orders: [],
      cartCount: '' // 购物车数量
    }
  },
  methods:{
    //获取订单数据
    getOrders(){                            //userid
      axios.get(`/api/order/check/user`).then(res => {
        if(res&&res.status===200){
          console.log("用户订单数据"+res.data)
          console.log(JSON.stringify( res.data, null, 2))
          this.orders = res.data
        }

      })
    },
    //获取购物车数量
    async getCartCount() {
      try {
        const response = await axios.get('/api/cart/getCartCount');
        if(response&&response.status === 200) this.cartCount = response.data;
      } catch (error) {
        console.error('获取购物车数量失败:', error);
      }
    },
    // 处理底部导航点击事件
    handleNavigate(path) {
      this.$router.push(path);
    },
    //确认订单
    confirmOrder(orderId){
      console.log("确认订单"+orderId)
      axios.get('/api/order/confirm/'+orderId).then(res => {
        if(!res||res.status !== 200) return;

        if( res.data === "success") {
          console.log("确认订单成功"+res)
          alert("确认订单成功")
          this.getOrders()
        }else if(res.data === "订单不存在") {
          console.log("订单不存在")
          alert("订单不存在")
        }else if(res.data === "订单状态不是未收货状态，不能确认收货"){

          alert("订单状态不是未收货状态")
        }else{
          console.log("确认订单失败"+res)
          alert("确认订单失败")
        }
      })

  },
    //取消订单
   cancelOrder(orderId){
    console.log("取消订单"+orderId)
    axios.get('/api/order/cancel/'+orderId).then(res => {
      if(res&&res.status === 200) {
        console.log("取消订单成功"+res)
        alert("取消订单成功")
        this.getOrders()
    }else{
          console.log("取消订单失败"+res)
          alert("取消订单失败")
      }
    })
  },
  //查看订单详情
    // 修改viewOrder方法\
    viewOrder(orderId) {
      this.$router.push({
        name: 'orderItem', // 使用命名路由
        params: { orderId }  // 传递参数
      })
    }
  },
  mounted(){
    this.getOrders()
  }

}

</script>